import { Injectable } from '@angular/core';
import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';

import { Observable, of, throwError } from 'rxjs';
import { catchError } from 'rxjs/internal/operators';
import { Router } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {
  constructor(private router: Router) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // const url = 'host';
    const authReq = req.clone({
      // url: url + req.url,
      // headers: req.headers.set('token', localStorage.getItem('token')),
    });
    return next.handle(authReq).pipe(
      catchError((err: HttpErrorResponse) => this.handleError(err))
    );
  }

  private handleError(
    event: HttpResponse<any> | HttpErrorResponse | any,
  ): Observable<any> {
    // 业务处理：一些通用操作
    console.log(event);
    switch (event.status) {
      case 401:
        console.log('need login');
        this.router.navigate(['/login']);
        return of(event);
      case 404:
        break;
      case 500:
        console.log(event.error.error.details);
        break;
      default:
    }
    return throwError(event);
  }
}
